// 地址修改
const db = uniCloud.database();

const utils = require('quanzi-utils');
module.exports = {
    _before: async function() { // 通用预处理器
        this.userInfo = await utils.getUsetInfo(this);
    },
    // 将默认值全部设置为false
    async moRen(data) {
        return data
    },
    //添加地址
    async add(data) {
        if (!this.userInfo.uid) return;
        data.uId = this.userInfo.uid;
        if (data.moren) {
            await db.collection('mall-address').where({
                uId: this.userInfo.uid
            }).update({
                moren: false
            })
        }
        data.createTime = Date.now();

        return await db.collection('mall-address').add(data);
    },
    //查询地址
    async getList() {
        if (!this.userInfo.uid) return;
        return await db.collection('mall-address').where({
            uId: this.userInfo.uid
        }).orderBy("moren", "desc").orderBy("createTime", "desc").get()
    },
    //修改默认值为true
    async updateMoren(data) {
        await db.collection('mall-address').where({
            uId: this.userInfo.uid
        }).update({
            moren: false
        })
        return await db.collection('mall-address').doc(data._id).update({
            moren: true
        })
    },
    // 获取一条地址信息
    async getOne(_id) {
        return await db.collection('mall-address').doc(_id).get();
    },
    //修改一条数据
    async updateOne(data) {
        if (!this.userInfo.uid) return;
        if (data.moren) {
            await db.collection('mall-address').where({
                uId: this.userInfo.uid
            }).update({
                moren: false
            })
        }
        data.createTime = Date.now();
        let newData = {
            ...data
        };
        delete newData._id
        return await db.collection('mall-address').doc(data._id).update(newData);
    },
    //获取默认地址
    async getMoernAddress() {
        if (!this.userInfo.uid) return;
        return await db.collection('mall-address').where({
            uId: this.userInfo.uid,
            moren: true
        }).get();
    }
}